package freespiritsocial.io.user.ui.fragment.account

import android.Manifest
import android.os.Bundle
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.permissionx.guolindev.PermissionX
import com.scwang.smart.refresh.layout.util.SmartUtil.dp2px
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseFragment
import freespiritsocial.io.user.data.model.bean.UserInfo
import freespiritsocial.io.user.databinding.FrgDiscoverPeopleBinding
import freespiritsocial.io.user.decoration.SpaceItemDecoration
import freespiritsocial.io.user.ext.goMain
import freespiritsocial.io.user.ext.init
import freespiritsocial.io.user.ui.activity.MainAct
import freespiritsocial.io.user.ui.adapter.PeopleAdapter
import freespiritsocial.io.user.util.ContactsHelper
import freespiritsocial.io.user.viewmodel.DiscoverFriendViewModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.util.StatusBarUtil

// TODO 能返回注册页面吗？
class DiscoverPeopleFrg: BaseFragment<DiscoverFriendViewModel,FrgDiscoverPeopleBinding>() {
    private val adapter by lazy(LazyThreadSafetyMode.NONE) {
        PeopleAdapter().apply {
            setOnItemChildClickListener { adapter,view,position ->
                val userInfo = data[position]
                when (view.id) {
                    R.id.tv_follow -> {
                        mViewModel.attention(userInfo.userId,userInfo.isFollowed)
                    }
                }
            }
        }
    }

    override fun layoutId(): Int = R.layout.frg_discover_people

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.darkMode(requireActivity())
        mDatabind.viewModel = mViewModel
        mDatabind.click = Click()
        getContacts()
        mDatabind.recyclerView.init(adapter,emptyImage = R.mipmap.empty_people,emptyText = "No friends have been found yet.")
            .addItemDecoration(SpaceItemDecoration(0,dp2px(15f)))
    }

    val act by lazy {
        activity as MainAct
    }
    var facebookEnable = true

    override fun createObserver() {
        super.createObserver()
        eventViewModel.attentionEvent.observe(this) { id ->
            adapter.data.forEachIndexed { index,userInfo ->
                if (userInfo.userId == id) {
                    userInfo.changeFollowStatus()
                    adapter.notifyItemChanged(index)
                    return@observe
                }
            }
        }
    }

    private fun initFacebook() {
        LoginManager.getInstance()
            .registerCallback(act.callbackManager,object: FacebookCallback<LoginResult> {
                override fun onSuccess(result: LoginResult?) {
                    if (isHidden) return
                    result?.accessToken?.let { token ->
                        mViewModel.facebookFriend(token) {
                            mViewModel.findFriends(it) {
                                adapter.addData(it.map { pojo ->
                                    UserInfo(userAvatar = pojo.user_avatar,userId = pojo.user_id,userName = pojo.user_name,name = pojo.name)
                                })
                                facebookEnable = false
                            }
                        }
                    }
                    LoginManager.getInstance().logOut()
                }

                override fun onCancel() {
                }

                override fun onError(error: FacebookException?) {
                }
            })

    }

    private fun getContacts() {
        PermissionX.init(this)
            .permissions(Manifest.permission.READ_CONTACTS)
            .request { allGranted,_,_ ->
                if (allGranted) {
                    //todo 获取通讯录
                    mViewModel.findFriends(ContactsHelper(requireContext()).phone.map { it.contactPhone }) {
                        adapter.addData(it.map { pojo ->
                            UserInfo(userAvatar = pojo.user_avatar,userId = pojo.user_id,userName = pojo.user_name,name = pojo.name)
                        })
                    }
                }
            }
    }

    override fun onDestroyView() {
        LoginManager.getInstance().unregisterCallback(act.callbackManager)
        super.onDestroyView()
    }

    inner class Click {
        fun findWithFacebook() {
            if (facebookEnable.not()) return
            initFacebook()
            LoginManager.getInstance()
                .logInWithReadPermissions(
                    act,
                    listOf("public_profile","user_friends")
                )
        }

        fun next() {
            nav().goMain()
        }
    }
}